﻿//
//  ZHDataService.m
//  WDFans
//
//  Created by Zhihong Yuan on 2/8/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ZHDataService.h"
#import "JSON.h"
#import "WDNews.h"
#import "WDUserMessage.h"
#import "WDProvince.h"
#import "WDDealer.h"
#import "WDForumSection.h"
#import "WDForum.h"
#import "WDThemes.h"

@interface ZHDataService(LocalUser)

- (NSString *)pathForLocalUserFile;
- (void)loadLocalUsers;

@end

@implementation ZHDataService

@synthesize loginUser = loginUser_;
@synthesize engine = engine_;
@synthesize localUsers = localUsers_;

#pragma mark - singleton design
- (void)dealloc
{
    [localUsers_ release];
    [engine_ release];
    engine_ = nil;
    [loginUser_ release];
    [super dealloc];
}

- (id)init
{
    if(self = [super init])
    {
        [self loadLocalUsers];
        
        WDUsers *user = [[WDUsers alloc] init];
        self.loginUser = user;
        [user release];
        
        OAuthEngine *e = [[OAuthEngine alloc] initOAuthWithDelegate: self];
        e.consumerKey = SinaWeiBoSDKDemo_APPKey;
        e.consumerSecret = SinaWeiBoSDKDemo_APPSecret;
        self.engine = e;
        [e release];
        e = nil;
    }
    return self;
}

+ (id)hiddenAlloc
{
    return [super alloc];
}

+ (id)alloc
{
    NSLog(@"Use +sharedInstance instead of +alloc.");
    return nil;
}

+ (id)new
{
    return [self alloc];
}

- (id)copyWithZone:(NSZone *)zone
{
    NSLog(@"Users: attempt to -copy may be a bug(singleton)");
    return self;
}

- (id)mutableCopyWitZone:(NSZone *)zone
{
    return [self copyWithZone:zone];
}

#pragma mark - local users
- (NSString *)pathForLocalUserFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths lastObject];
    return [documentDirectory stringByAppendingPathComponent:@"localUsers"];
}

- (void)loadLocalUsers
{
    NSData *data = [NSData dataWithContentsOfFile:[self pathForLocalUserFile]];
    self.localUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    if(nil == self.localUsers)
        self.localUsers = [NSMutableArray array];
}

- (void)saveLocalUsers
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.localUsers];
    [data writeToFile:[self pathForLocalUserFile] atomically:NO];
}

#pragma mark - login user

+ (BOOL)isLogined
{
    if([[self sharedService] loginUser].userId == nil || [[[self sharedService] loginUser].userId isEqualToString:@""])
        return NO;
    return YES;
}

+ (void)logout
{
    [[self sharedService] loginUser].userId = nil;
    [[self sharedService] loginUser].userName = nil;
    [[self sharedService] loginUser].userEmail = nil;
    [[self sharedService] loginUser].userGrouptitle = nil;
    [[self sharedService] loginUser].userProvince = nil;
    [[self sharedService] loginUser].userCity = nil;
    [[self sharedService] loginUser].userAvatarurl = nil;
    [[self sharedService] loginUser].userRegdate = nil;
    [[self sharedService] loginUser].userPwd = nil;
}

#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}

#pragma mark - data services methods

+ (ZHDataService *)sharedService
{
    static dispatch_once_t once;    
    static ZHDataService *dataService = nil;
    
    dispatch_once(&once, ^{
        dataService = [[ZHDataService hiddenAlloc] init];
    });
    return dataService;
}


#pragma mark - parse data to Objects
+ (NSDictionary *)parseToNewesWithData:(NSData *)data
{
//    NSArray *a = [NSKeyedUnarchiver unarchiveObjectWithData:data];
//    NSData *d = [NSKeyedArchiver archivedDataWithRootObject:a];
    //NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
//    //NSLog(@"succeed:s=%@",s);
    NSDictionary *responseDictionary = [s JSONValue];

    if(responseDictionary)
    {
        NSMutableArray *returnNewsArray = [NSMutableArray array];
        NSArray *newsArray = [responseDictionary objectForKey:@"NewsList"];
        NSString *page = [responseDictionary objectForKey:@"page"];
        for(NSDictionary *dict in newsArray)
        {
            WDNews *n = [[WDNews alloc] init];
            [n setNewsTitle:[dict objectForKey:@"title"]];
            [n setNewsDescription:[dict objectForKey:@"summary"]];
            [n setNewsImageUrl:[dict objectForKey:@"coverimage"]];
            [n setNewsDate:[dict objectForKey:@"time"]];
            [n setNewsContent:[dict objectForKey:@"content"]];
            [returnNewsArray addObject:n];
            [n release];
        }
        NSDictionary *returnDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:returnNewsArray,page, nil] forKeys:[NSArray arrayWithObjects:@"recentNews",@"page", nil]];
        return returnDict;
    }
    return nil;
}

+ (NSDictionary *)parseToPersonalMessagesWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        NSMutableArray *messages = [NSMutableArray array];
        NSArray *mesArray = [responseDictionary objectForKey:@"Messagelist"];
        NSString *page = [responseDictionary objectForKey:@"page"];
        for(NSDictionary *dict in mesArray)
        {
            WDUserMessage *m = [[WDUserMessage alloc] init];
            m.mesTitle = [dict objectForKey:@"title"];
            m.mesContent = [dict objectForKey:@"content"];
            m.mesDate = [dict objectForKey:@"time"];
            m.mesId = [[dict objectForKey:@"gpmid"] intValue];
            m.mesIsRead = [[dict objectForKey:@"isread"] boolValue];
            [messages addObject:m];
            [m release];
        }
        NSDictionary *returnDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:messages,page, nil] forKeys:[NSArray arrayWithObjects:@"personalMessages",@"page", nil]];
        return returnDict;
    }
    return nil;
}

+ (BOOL)setMessageReadSucceed:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    return [s intValue];
}

+ (BOOL)parseToLoginUserWithData:(NSData *)data
{
    //sava login user data to [DataService loginUser]
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    if ([s isEqualToString:@"userid=0"]) {
        return NO;
    }
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        NSDictionary *dict = [responseDictionary objectForKey:@"UserInfo"];
        [[self sharedService] loginUser].userId = [dict objectForKey:@"uid"];
        [[self sharedService] loginUser].userEmail = [dict objectForKey:@"email"];
        [[self sharedService] loginUser].userName = [dict objectForKey:@"username"];
        [[self sharedService] loginUser].userRegdate = [dict objectForKey:@"regdate"];
        [[self sharedService] loginUser].userCredits = [[dict objectForKey:@"credits"] intValue];
        [[self sharedService] loginUser].userNewpm = [[dict objectForKey:@"newpm"] intValue];
        [[self sharedService] loginUser].userOldpm = [[dict objectForKey:@"oldpm"] intValue];
        [[self sharedService] loginUser].userAvatarurl = [dict objectForKey:@"avatarurl"];
        [[self sharedService] loginUser].userGrouptitle = [dict objectForKey:@"grouptitle"];
        [[self sharedService] loginUser].userProvince = [dict objectForKey:@"province"];
        [[self sharedService] loginUser].userCity = [dict objectForKey:@"city"];
        [[self sharedService] loginUser].authcode = [dict objectForKey:@"authcode"];
        NSLog(@"authcode=%@",[[self sharedService] loginUser].authcode);
        
    }
    return YES;
}

+ (NSDictionary *)parseToAllProvincesWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        //get all other dealers
        NSDictionary *dict = [responseDictionary objectForKey:@"provincelist"];
        NSArray *otherProvinces = [dict allValues];
        NSMutableArray *array = [NSMutableArray array];
        for(NSDictionary *dict in otherProvinces)
        {
            WDProvince *p = [[WDProvince alloc] init];
            p.provinceId = [[dict objectForKey:@"provinceid"] intValue];
            p.provinceName = [dict objectForKey:@"province"];
            p.dealerNum = [[dict objectForKey:@"counts"] intValue];
            [array addObject:p];
            [p release];
        }
        //get current location dealer
        NSDictionary *dictForLocation = [responseDictionary objectForKey:@"location"];
        WDProvince *curProvince = [[WDProvince alloc] init];
        curProvince.provinceId = [[dictForLocation objectForKey:@"provinceid"] intValue];
        curProvince.provinceName = [dictForLocation objectForKey:@"province"];
        curProvince.dealerNum = [[dictForLocation objectForKey:@"counts"] intValue];
        
        NSDictionary *returnDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:array,curProvince, nil] forKeys:[NSArray arrayWithObjects:@"otherProvinces",@"currentProvince", nil]];
        [curProvince release];
        return returnDict;

    }
    return nil;
}

+ (NSArray *)parseToAllDealersWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        //get all other dealers
        NSArray *dealers = [responseDictionary objectForKey:@"dealerlist"];
        NSMutableArray *array = [NSMutableArray array];
        for(NSDictionary *dict in dealers)
        {
            WDDealer *d = [[WDDealer alloc] init];
            d.dealerId = [NSString stringWithFormat:@"%@",[dict objectForKey:@"dealerid"]];
            d.name = [dict objectForKey:@"company"];
            d.address = [dict objectForKey:@"address"];
            d.zipcode = [dict objectForKey:@"zipcode"];
            d.contact = [dict objectForKey:@"contact"];
            d.telephone = [dict objectForKey:@"telephone"];
            d.lattitude = [[dict objectForKey:@"lat"] floatValue];
            d.longitude = [[dict objectForKey:@"lng"] floatValue];
            [array addObject:d];
            [d release];
        }
        return array;
    }
    return nil;
}

+ (NSMutableArray *)parseToForumSectionsWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        NSMutableArray *allSections = [NSMutableArray array];
        NSDictionary *sections = [responseDictionary objectForKey:@"forumlist"];
        for(NSString *sid in [sections allKeys])
        {
            WDForumSection *fs = [[WDForumSection alloc] init];
            fs.sectionId = [sid intValue];
            NSDictionary *d = [sections objectForKey:sid];
            fs.name = [d objectForKey:@"name"];
            NSDictionary *forums = [d objectForKey:@"forums"];
            for(NSString *fid in [forums allKeys])
            {
                WDForum *f = [[WDForum alloc] init];
                f.forumId = [fid intValue];
                NSDictionary *d1 = [forums objectForKey:fid];
                f.icon = [d1 objectForKey:@"icon"];
                f.name = [d1 objectForKey:@"name"];
                f.description = [d1 objectForKey:@"description"];
                f.threads = [[d1 objectForKey:@"threads"] intValue];
                f.posts = [[d1 objectForKey:@"posts"] intValue];
                f.todayPosts = [[d1 objectForKey:@"todayposts"] intValue];
                f.displayUrl = [d1 objectForKey:@"display_url"];
                [fs.forums addObject:f];
                [f release];
            }
            [allSections addObject:fs];
            [fs release];
        }
        return allSections;
    }
    return nil;
}

+ (NSMutableDictionary *)parseToThemesWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        NSMutableDictionary *returnDict = [NSMutableDictionary dictionary];
        [returnDict setObject:[responseDictionary objectForKey:@"page"] forKey:@"isNextPageExist"];
        NSMutableArray *returnThemes = [NSMutableArray array];
        NSArray *themes = [responseDictionary objectForKey:@"threadlist"];
        for(NSDictionary *dict in themes)
        {
            WDThemes *t = [[WDThemes alloc] init];
            t.tid = [[dict objectForKey:@"tid"] intValue];
            t.fid = [[dict objectForKey:@"fid"] intValue];
            t.aid = [[dict objectForKey:@"authorid"] intValue];
            t.author = [dict objectForKey:@"author"];
            t.subject = [dict objectForKey:@"subject"];
            t.dateLine = [dict objectForKey:@"dateline"];
            t.lastPost = [dict objectForKey:@"lastpost"];
            t.lastPoster = [dict objectForKey:@"lastposter"];
            t.viewCount = [[dict objectForKey:@"view"] intValue];
            t.replies = [[dict objectForKey:@"replies"] intValue];
            t.viewThreadUrl = [dict objectForKey:@"viewthread_url"];
            [returnThemes addObject:t];
            [t release];
        }
        [returnDict setObject:returnThemes forKey:@"themes"];
        return returnDict;
    }
    return nil;
}

+ (NSMutableDictionary *)parseToThemesDetailWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *responseDictionary = [s JSONValue];
    if(responseDictionary)
    {
        NSMutableDictionary *returnDict = [NSMutableDictionary dictionary];
        [returnDict setObject:[responseDictionary objectForKey:@"page"] forKey:@"isNextPageExist"];
        NSMutableArray *returnThemes = [NSMutableArray array];
        NSArray *themes = [responseDictionary objectForKey:@"forum"];
        for(NSDictionary *dict in themes)
        {
            WDThemes *t = [[WDThemes alloc] init];
            t.tid = [[dict objectForKey:@"tid"] intValue];
            t.fid = [[dict objectForKey:@"fid"] intValue];
            t.aid = [[dict objectForKey:@"authorid"] intValue];
            t.author = [dict objectForKey:@"author"];
            t.subject = [dict objectForKey:@"subject"];
            t.dateLine = [dict objectForKey:@"dateline"];
            t.lastPost = [dict objectForKey:@"lastpost"];
            t.lastPoster = [dict objectForKey:@"lastposter"];
            t.viewCount = [[dict objectForKey:@"view"] intValue];
            t.replies = [[dict objectForKey:@"replies"] intValue];
            t.viewThreadUrl = [dict objectForKey:@"viewthread_url"];
            [returnThemes addObject:t];
            [t release];
        }
        [returnDict setObject:returnThemes forKey:@"themes"];
        return returnDict;
    }
    return nil;
}

+ (NSString *)changeUserInfoWithData:(NSData *)data
{
    NSString *s = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"result:%@",s);
    if ([s isEqualToString:@"succeed"])
        return @"修改成功";
    else if([s isEqualToString:@"register_succeed"])
        return @"注册成功";
    else if([s isEqualToString:@"register_manual_verify"])
        return @"注册成功，等待审核";
    else if([s isEqualToString:@"register_disable"])
        return @"系统处于维护状态，站点关闭，不允许注册";
    else if([s isEqualToString:@"variable_submit_error"])
        return @" 提交的数据有错误，可能提交的不是一个数组";
    else if([s isEqualToString:@"profile_uid_duplicate"])
        return @"用户uid发生重复错误";
    else if([s isEqualToString:@"undefined_action"])
        return @"注册UC的时候发生未知错误";
    else if([s isEqualToString:@"profile_email_duplicate"])
        return @"Email已经被注册过";
    else if([s isEqualToString:@"profile_email_domain_illegal"])
        return @"Email所在的域不允许注册";
    else if([s isEqualToString:@"profile_email_illegal"])
        return @"Email输入错误";
    else if([s isEqualToString:@"profile_username_illegal"])
        return @"用户名包含敏感字符";
    else if([s isEqualToString:@"profile_username_illegal"])
        return @"用户名不合法";
    else if([s isEqualToString:@"register_flood_ctrl"])
        return @"所在ip24小时内注册次数太多";
    else if([s isEqualToString:@"register_ctrl"])
        return @"所在的ip地址两次注册间隔时间太短";
    else if([s isEqualToString:@"profile_username_protect"])
        return @"用户名包含被系统屏蔽的字符";
    else if([s isEqualToString:@"profile_username_duplicate"])
        return @"用户名重名";
    else if([s isEqualToString:@"username_is_exists"])
        return @"用户名已经存在";
    else if([s isEqualToString:@"profile_reside_none"])
        return @"所在地输入不正确";
    else if([s isEqualToString:@"profile_passwd_illegal"])
        return @"密码包含特殊字符";
    else if([s isEqualToString:@"profile_username_toolong"])
        return @"用户名长度太长";
    else if([s isEqualToString:@"profile_username_tooshort"])
        return @"用户名长度太短";
    else if([s isEqualToString:@"not_open_registration_invite_for_mobile"])
        return @"站点不允许使用手机进行邀请注册";
    else if([s isEqualToString:@"register_disable2"])
        return @"系统关闭了注册功能";
    else if([s isEqualToString:@"register_manual_verify"])
        return @"注册成功，等待审核";
    else if([s isEqualToString:@"register_manual_verify"])
        return @"注册成功，等待审核";
//    variable_[username|password|email|province|city]_format_error
//    涉及5个，是某个字段未提交或某字段的数据格式有错误。
//    
//    profile_[username|password|email|province]_empty
//    涉及4个字段，是某个字段为空。
    else
        return @"操作失败";
}
@end
